package com.itheima.tlias.tliasweb.interceptor;

import com.alibaba.fastjson2.JSON;
import com.itheima.tlias.tliasweb.pojo.Result;
import com.itheima.tlias.tliasweb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录信息的拦截
 * */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token的值
        String token = request.getHeader("token");
        // token为空
        if(!StringUtils.hasLength(token)){
            // 设置响应头中的code
            response.setStatus(200);
            // 设置响应体的数据格式
            response.setContentType("application/json;charset=UTF8");
            // 响应体数据
            Result result = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(result);
            // 输出到浏览器
            response.getWriter().write(json);
            return false;
        }else{
            try{
                // token解析
                Claims claims = JwtUtils.parseJWT(token);
                // 获取payload中的数据
                Integer id = claims.get("id", Integer.class);
                String username = claims.get("username", String.class);
                if(id != null && StringUtils.hasLength(username)){
                    // token解析是成功的
                    return true;
                }else {
                    // token解析是失败的
                    response.setStatus(200);
                    response.setContentType("application/json;charset=UTF8");
                    Result result = Result.error("NOT_LOGIN");
                    String json = JSON.toJSONString(result);
                    response.getWriter().write(json);
                    return false;
                }
            }catch(Exception e){
                log.error("token解析异常", e);
                response.setStatus(200);
                response.setContentType("application/json;charset=UTF8");
                Result result = Result.error("NOT_LOGIN");
                String json = JSON.toJSONString(result);
                response.getWriter().write(json);
                return false;
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
